#pragma once
#include "comm/util.hpp"
#include "comm/log.hpp"
#include "comm/httplib.h"

#include "oj_model2.hpp"
#include "oj_view.hpp"
#include <jsoncpp/json/json.h>

namespace ns_control
{
    using namespace std;
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;
    // ! 提供服务的主机

    /*
        @param ip 编译服务的ip
        @param port 编译服务的 端口
        @param load 编译服务的负载
        @param mutex 禁止拷贝， 使用指针
    */
    struct Machine
    {
    public:
        Machine() : ip(""), load(0), mtx(nullptr)
        {
        }
        ~Machine()
        {
        }

    public:
        // !提升主机负载
        void inLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        // !减少主机负载
        void decLoad()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }

        // !获取主机负载, 其实没有太大的意义就是为了统一接口
        uint64_t Load()
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();

            return _load;
        }

        void resetLoad()
        {
            if (mtx)
                mtx->lock();
            load = 0;
            if (mtx)
                mtx->unlock();
        }

    public:
        string ip;
        int port;
        uint64_t load;
        std::mutex *mtx;
    };

    // ! 负载均衡模块
    const string server_machine = "conf/server_machine.conf";
    class Loadblance
    {
    private:
        // *可以提供所有服务的主机
        vector<Machine> machines;
        // *所有在线的主机
        vector<int> online;
        // *所有离线主机
        vector<int> offline;
        // *保证数据安全
        std::mutex mtx;

    public:
        Loadblance()
        {
            assert(loadConf(server_machine));
            LOG(INFO) << "加载" << server_machine << " 成功" << std::endl;
        }
        ~Loadblance()
        {
        }
        bool loadConf(const string &machine_list)
        {
            std::ifstream in(machine_list);
            if (!in.is_open())
            {
                LOG(FATAL) << "server machine load failed!!" << std::endl;
                return false;
            }
            string line;
            while (std::getline(in, line))
            {
                vector<string> tokens;
                StringUtil::splitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "split " << line << " failed" << std::endl;
                    continue;
                }
                Machine m;
                m.ip = tokens[0];
                m.port = std::stoi(tokens[1]);
                m.load = 0;
                m.mtx = new std::mutex();

                online.push_back(machines.size());
                machines.emplace_back(m);
            }
            in.close();

            return true;
        }
        /*
            @note
            ```
            * 1. 使用选择好的主机(更新该主机的负载)
            * 2. 可能需要离线该主机
            *
            @param

            ```
        */
        bool smartSelect(int &id, Machine **ma)
        {

            mtx.lock();
            // =负载均衡的算法
            /*
                & 随机数 + hash
                & 轮询 + hash
            */
            if (!online.size())
            {
                LOG(FATAL) << "所有的后端编译器主机都已经离线, 请 运维的同事尽快查看！" << std::endl;
                mtx.unlock();
                return false;
            }
            id = online[0];
            uint64_t min_load = machines[online[0]].Load();
            for (auto &m : online)
            {
                auto curr_load = machines[m].Load();
                if (min_load >= curr_load)
                {
                    min_load = curr_load;
                    id = m;
                    *ma = &machines[m];
                }
            }
            auto m = **ma;
            mtx.unlock();
            return true;
        }
        void offlineMachine(int which)
        {
            mtx.lock();
            auto iter = std::find(online.begin(), online.end(), which);
            if (iter != online.end())
            {
                // * 这出现的问题就是在这个主机下线的时候他的负载没有被清理
                machines[which].resetLoad();
                online.erase(iter);
                offline.emplace_back(which);
            }
            mtx.unlock();
        }
        void onlineMachine()
        {
            // * 后面统一上线
            mtx.lock();

            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();
            LOG(INFO) << "所有的主机又上线了" << std::endl;
        }
        // ** for test
        void showMachines()
        {
            mtx.lock();
            cout << "当前在线主机列表: ";
            for (auto &id : online)
            {
                cout << id << " ";
            }
            cout << endl;
            cout << "当前离线主机数量:";
            for (auto &id : offline)
            {
                cout << id << " ";
            }
            cout << endl;
            mtx.unlock();
        }
    };

    class Control
    {
    private:
        Model _model;
        View _view;
        Loadblance _load_blance;

    public:
        /*
            @brief 根据题目的数据转换为html的中转站， 获取所有题目的列表，转换为前端界面
        */
        void recoverMachine()
        {
            _load_blance.onlineMachine();
        }
        bool allQuestions(string *html)
        {
            vector<Question> all;
            bool ret;
            if (_model.getAllQuestion(&all))
            {
                std::sort(all.begin(), all.end(), [](Question &q1, Question &q2)
                          { return std::stoi(q1.number) < std::stoi(q2.number); });
                // ? 此时获取题目信息成功构建 html网页返回出去
                _view.allExpandHtml(all, html);
                ret = true;
            }
            else
            {
                *html = "获取题目链表失败";
                ret = false;
            }
            return ret;
        }
        /*
            @brief  获取单个题目的描述和代码编辑 html
        */
        bool question(const string &number, string *html)
        {
            Question q;
            if (_model.getOneQuestion(number, &q))
            {
                // ?此时获取一个题目成功, 转换为网页
                _view.oneExpandHtml(q, html);
                return true;
            }
            return false;
        }

        /*
        @note
        ```
        用户提交上来的字段包括这些
            * id
            * code :#include ...
            * input: ""

            =1. in_json进行反序列化，得到用户id，得到用户的源代码， input
            =2. 重新拼接用户的代码和 header,形成新的代码
            =3. 选择负载最低的主机。(差错处理)
            =4. 发起http请求，得到结果
            =5. *out_json = 结果
            * ```
        */
        void judge(const string &number,
                   const string &in_json, string *out_json)
        {
            // LOG(INFO) << "in_json: " << in_json << std::endl
            //           << "number: " << number << std::endl;
            Question q;
            _model.getOneQuestion(number, &q);
            LOG(DEBUG) << "获取到" << number << "题目的信息" << std::endl;
            /*
            = the usage of jsonCpp
            Json::StreamWriterBuilder builder;
            builder["emitUTF8"] = true;
            std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
            std::stringstream ss;
            writer->write(out_value, &ss);
            */
            // &1
            Json::Value in_value;
            Json::Reader reader;
            reader.parse(in_json, in_value);
            auto code = in_value["code"].asString();
            // &2
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;

            Json::StreamWriterBuilder builder;
            builder["emitUTF8"] = true;
            std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
            std::stringstream ss;
            writer->write(compile_value, &ss);
            auto compile_string = ss.str();

            // &3
            /*规则：一直选，直到主机可用， 否则，就全部挂掉*/
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_load_blance.smartSelect(id, &m))
                {
                    break;
                }
                LOG(INFO) << "select the host successfully, and its id is :" << id << std::endl
                          << "details:" << m->ip << ":" << m->port << std::endl;
                // &4
                Client client(m->ip, m->port);
                m->inLoad();
                LOG(INFO) << "select the host successfully, and its id is : " << id << std::endl
                          << "details: " << m->ip << ": " << m->port << "当前主机的负载为: " << m->Load() << std::endl;
                // &4
                if (auto res = client.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // &5
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->decLoad();
                        LOG(INFO) << "请求编译和运行服务成功" << endl;
                        break;
                    }
                    m->decLoad();
                }
                else
                {
                    // 请求失败
                    LOG(INFO) << "select the host successfully, and its id is :" << id << std::endl
                              << "details:" << m->ip << ":" << m->port << "可能已经离线" << std::endl;
                    _load_blance.offlineMachine(id);
                    // ? build to debug
                    _load_blance.showMachines();
                }
            }
        }
    };
}